﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "settingdialog.h"
#include "historydialog.h"
#include "sqlthread.h"
#include <QtCharts>
#include <QMetaType>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_axisX(new QValueAxis())
    , m_axisY(new QValueAxis())
    , group(new QButtonGroup())
    , ui(new Ui::MainWindow)
{
    qDebug() << "mainwindow "<<QThread::currentThreadId()<<endl;
    //ports
    injector_port = new SerialDriver();

    //DTU
    dtu = new DTUManager();

    connect(dtu, &DTUManager::sigShowData, this, &MainWindow::showDTUData);

    //injector
    injector = new InjectorManager(injector_port);
    if(injector_port->open("COM4"))
    {
        QIODevice::connect(injector_port->m_serial, &QSerialPort::readyRead, injector, &InjectorManager::handlePort);
        connect(this, &MainWindow::signalUpdateSetting, injector, &InjectorManager::updateSetting);
        connect(injector, &InjectorManager::updateStatus, this, &MainWindow::updateInjectorStatus);
        qDebug()<<"COM4 opened"<<endl;
    }
    //mysql thread
    sqlThread = new SqlThread();
    //tcp thread
    tcpThread = new TCPThread();

    //sql injector connect
    connect(this, &MainWindow::sigSearchInj, sqlThread, &SqlThread::searchDataInj);
    connect(sqlThread, &SqlThread::sigSearchDataInj, this, &MainWindow::exportFile);
    connect(injector, &InjectorManager::sigUploadDataInj, sqlThread, &SqlThread::uploadDataInj);

    //sql dtu connect
    connect(tcpThread, &TCPThread::sigDTUUpload, sqlThread, &SqlThread::uploadDataDTU);
    connect(this, &MainWindow::sigSearchDTU, sqlThread, &SqlThread::searchDataDTU);
    connect(sqlThread, &SqlThread::sigSearchDataDTU, this, &MainWindow::showDTUHistory);

    //tcp dtu connect //ui
    connect(tcpThread, &TCPThread::sigDTUUpdate, dtu, &DTUManager::slotDTUUpdate);
    sqlThread->start();
    tcpThread->start();

    qDebug() << "connected"<<endl;
    //main window
    ui->setupUi(this);
    setFixedSize(this->width(), this->height());;
    connect(ui->settingButton, &QPushButton::clicked, this, &MainWindow::showSettingDialog);
    connect(ui->radioButton_0, &QRadioButton::clicked, this, &MainWindow::routeSwitched);
    connect(ui->radioButton_1, &QRadioButton::clicked, this, &MainWindow::routeSwitched);
    connect(ui->radioButton_2, &QRadioButton::clicked, this, &MainWindow::routeSwitched);
    connect(ui->radioButton_3, &QRadioButton::clicked, this, &MainWindow::routeSwitched);

    connect(ui->historyButton, &QPushButton::clicked, this, &MainWindow::showINJHistoryDialog);

    group->addButton(ui->radioButton_0, 0);
    group->addButton(ui->radioButton_1, 1);
    group->addButton(ui->radioButton_2, 2);
    group->addButton(ui->radioButton_3, 3);

    ui->tabWidget->setTabText(0, QStringLiteral("DTU实时曲线"));
    ui->tabWidget->setTabText(1, QStringLiteral("DTU历史曲线"));

    historyChart = new QChart();

    historyChart->addAxis(m_axisX,Qt::AlignBottom);
    historyChart->addAxis(m_axisY,Qt::AlignLeft);
    historyChart->legend()->hide();
    ui->historyGraphicsView->setChart(historyChart);
    //historyChart->addSeries(sqlThread->series);
    //m_axisX->setTickCount(20);
    //m_axisX->setRange(0, 30);
    m_axisX->setTitleText(QStringLiteral("时间(ms)"));
    m_axisY->setTitleText(QStringLiteral("电流(mA)"));
    m_axisY->setRange(0, 25);

    connect(ui->tabWidget, &QTabWidget::tabBarClicked, this, &MainWindow::showDTUHistoryDialog);

    ui->radioButton_0->setChecked(true);
    ui->graphicsView->setChart(dtu->getChart(0));


}

MainWindow::~MainWindow()
{
    delete sqlThread;
    delete tcpThread;
    tcpThread->quit();
    tcpThread->wait();
    sqlThread->quit();
    sqlThread->wait();

    delete injector_port;
    delete injector;
    delete dtu;
    delete ui;
}

void MainWindow::updateInjectorStatus()
{
    ui->c_progressBar_0->setValue(injector->injector[0].status_battery);
    ui->o_progressBar_0->setValue(injector->injector[0].status_volremain);
    ui->c_progressBar_1->setValue(injector->injector[1].status_battery);
    ui->o_progressBar_1->setValue(injector->injector[1].status_volremain);
    ui->c_progressBar_2->setValue(injector->injector[2].status_battery);
    ui->o_progressBar_2->setValue(injector->injector[2].status_volremain);
    ui->c_progressBar_3->setValue(injector->injector[3].status_battery);
    ui->o_progressBar_3->setValue(injector->injector[3].status_volremain);
}

void MainWindow::showSettingDialog()
{
    SettingDialog sDialog(injector->getSetting());
    if(sDialog.exec())
    {
        qDebug() << "accepted"<<endl;
        QList<Setting> settingList = sDialog.getSettings();
        emit signalUpdateSetting(settingList);
    }

}

void MainWindow::showDTUHistoryDialog(int idx)
{
    if(idx == 1)
    {
        HistoryDialog hDialog;
        if(hDialog.exec())
        {
            qDebug() << "history" <<endl;
            int id = hDialog.idxEdit->value();
            QDateTime time = hDialog.timeDateEdit->dateTime();
            emit sigSearchDTU(time, id);
        }       
    }
}
void MainWindow::showDTUHistory(QSplineSeries* series)
{
    static bool first = true;
    if(first)
    {
        historyChart->addSeries(series);
        first = false;
        series->attachAxis(m_axisX);
        series->attachAxis(m_axisY);
    }
    qDebug() << "complete"<<endl;
}

void MainWindow::showDTUData(int idx, int data)
{
    auto p = ui->lineEdit_0;
    switch(idx)
    {
        case 0: p = ui->lineEdit_0;break;
        case 1: p = ui->lineEdit_1;break;
        case 2: p = ui->lineEdit_2;break;
        case 3: p = ui->lineEdit_3;break;
        default: break;
    }
    p->setText(QString::number(data));
}

void MainWindow::routeSwitched()
{
    int id = group->checkedId();
    //qDebug() << "real time "<<id <<endl;
    ui->graphicsView->setChart(dtu->getChart(id));
}

void MainWindow::showINJHistoryDialog()
{
    SmallHistoryDialog hDialog;
    if(hDialog.exec())
    {
        QDate date = hDialog.timeDateEdit->date();
        emit sigSearchInj(date);
    }
}

void MainWindow::exportFile(const QString& context, const QDate& date)
{
    QString filename = QFileDialog::getSaveFileName(this,
                      QStringLiteral("保存路径"), date.toString("yyyy-MM-dd") + ".log",
                      QStringLiteral("日志文件(*.log)"));
    if(filename.size() != 0)
    {
        QFile file(filename);
        file.open(QIODevice::ReadWrite);

        if(file.isOpen())
        {
            QTextStream out(&file);
            out << context;
            out.flush();
            file.close();
        }
    }
}



